﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Tools
{
    /// <summary>
    /// Cmd命令运行工具
    /// </summary>
    public class ShellCmd
    {
        private string result;
        private string errinf;
        private Process process;
        private bool disposed;

        public ShellCmd() { disposed = false; }

        /// <summary>
        /// 是否忽略错误流（true可防卡死，但拿不到可能有的错误信息）
        /// </summary>
        public bool IngoreError { get; set; }
        /// <summary>
        /// 获取命令运行后的结果（包括全部命令行）
        /// </summary>
        public string Result { get { return result; } }
        /// <summary>
        /// 获取命令运行后的错误信息（如果有）
        /// </summary>
        public string Errinf { get { return errinf; } }
        /// <summary>
        /// 是否释放了
        /// </summary>
        public bool Disposed { get { return disposed; } }
        /// <summary>
        /// 强制中止
        /// </summary>
        public void Dispose()
        {
            if (process != null && !process.HasExited)
            {
                process.Kill();
                process.Dispose();
                disposed = true;
            }
        }
        /// <summary>
        /// 运行cmd命令
        /// </summary>
        /// <param name="cmds">命令组</param>
        /// <param name="waitForExit">是否等待退出</param>
        /// <param name="needResult">是否需要获取输出结果</param>
        public void Run(string[] cmds, bool waitForExit = true, bool needResult = true)
        {
            result = errinf = string.Empty;
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "/c C:\\Windows\\System32\\cmd.exe";
            startInfo.UseShellExecute = false;//不使用系统外壳程序启动 
            startInfo.RedirectStandardInput = false;//不重定向输入 
            startInfo.RedirectStandardOutput = true;//重定向输出 
            startInfo.RedirectStandardError = IngoreError ? false : true;
            startInfo.CreateNoWindow = false;//不创建窗口 
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.Verb = "RunAs";//
            process = Process.Start(startInfo);
            StreamWriter input = process.StandardInput;
            StreamReader output = process.StandardOutput;
            StreamReader error = null;
            if (!IngoreError) error = process.StandardError;
            foreach (string cmd in cmds)
            {
                input.WriteLine(cmd);
                input.Flush();
            }
            input.Close();
            if (needResult) result = output.ReadToEnd();
            output.Close();
            if (!IngoreError)
            {
                errinf = error.ReadToEnd();
                error.Close();
            }
            if (waitForExit) process.WaitForExit();
            process.Close();
        }
    }
}